using System;
using System.Xml;
using LibGreen.Jabber.Connection;
using LibGreen.Jabber.Delegates;

namespace LibGreen.Jabber.ProtocolElements.SaslElements
{
    /// <summary>
    /// Defines a &lt;failure&gt; element
    /// </summary>
    class FailureElement
    {
        private readonly SaslFailureReason reason = SaslFailureReason.Unknown;

        /// <summary>
        /// Initializes a FailureElement from a received <see cref="Element"/>
        /// </summary>
        /// <param name="element">The received <see cref="Element"/> containing the &lt;failure&gt; stanza</param>
        public FailureElement(Element element)
        {
            // Scan the element's children for the error reason
            foreach (Element child in element.Children)
            {
                switch (child.Name.ToLowerInvariant())
                {
                    case "aborted":
                        reason = SaslFailureReason.Aborted;
                        break;
                    case "incorrect-encoding":
                        reason = SaslFailureReason.IncorrectEncoding;
                        break;
                    case "invalid-mechanism":
                        reason = SaslFailureReason.InvalidMechanism;
                        break;
                    case "mechanism-too-weak":
                        reason = SaslFailureReason.MechanismTooWeak;
                        break;
                    case "not-authorized":
                        reason = SaslFailureReason.BadCredentials;
                        break;
                    case "temporary-auth-failure":
                        reason = SaslFailureReason.TemporaryAuthenticationFailure;
                        break;
                }
            }
        }

        /// <summary>
        /// Gets the reason for the SASL negotiation failure
        /// </summary>
        public SaslFailureReason Reason
        {
            get { return reason; }
        }
    }
}
